package com.zb.chat.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

import org.junit.Test;

/**
 * @author: zhaobin
 * @date: 2024/3/3 14:05
 * @Description: 聊天室客户端
 */
public class ChatClient {

    /**
     * 启动方法
     */
    public void startClient(String name) {
        System.out.print(name + "，你好，");
        SocketChannel sc = null;
        try {
            // 1、创建选择器
            Selector selector = Selector.open();
            // 2、创建客户端通道，连接服务端
            sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8000));
            // 3、设置为非阻塞模式
            sc.configureBlocking(false);
            // 4、把通道注册到选择器
            sc.register(selector, SelectionKey.OP_READ);
            // 5、创建新线程，接收消息
            new Thread(new ClientThread(selector)).start();

            // 6、向服务端发送消息
            Scanner scanner = new Scanner(System.in);
            String msg = "";
            while (scanner.hasNextLine()) {
                msg = scanner.nextLine();
                if (msg.length() > 0) {
                    sc.write(Charset.forName("utf8").encode(name + "：" + msg));
                }
            }
        } catch (IOException e) {
            //e.printStackTrace();
        } finally {
            // 关闭
            try {
                if (sc != null) {
                    sc.close();
                }
                System.out.println("客户端已关闭！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
